import fcntl, socket, struct, string

def getHwAddr(ifname,format="string"):
    '''Retrieves MAC address for the given interface'''
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    info = fcntl.ioctl(s.fileno(), 0x8927,  struct.pack('256s', ifname[:15]))
    if format == "string":
        return ''.join(['%02x:' % ord(char) for char in info[18:24]])[:-1]
    elif format == "hex":
        return info[18:24]
    
def get_ip_address(ifname,format="string"):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    info = fcntl.ioctl(s.fileno(),0x8915,struct.pack('256s', ifname[:15]))
    if format == "string":
        return socket.inet_ntoa(info[20:24])
    elif format == "hex":
        return info[20:24]
    
def isBroadcast(macaddress):
    if macaddress == "\xff\xff\xff\xff\xff\xff":
        return True
    else:
        return False

def its(lst):
    '''Returns IP address as string using the provided hex values list'''
    return string.join([str(ord(value)) for value in lst],".")
def mts(lst):
    '''Returns MAC address as string using the provided hex values list'''
    return string.join([str(hex(ord(value)))[2:] for value in lst],":")
def sti(address):
    ''' Returns hex value of the given string ip address'''
    chars = string.split(address,".")
    ipstr = ""
    for octet in chars:
        ipstr = ipstr + chr(int(octet))
    return ipstr
def stm(mac):
    ''' Returns hex string for given mac address string like aa:bb:cc:dd:ee:ff'''
    chars = string.split(mac,":")
    macstr = ""
    for value in chars:
        macstr = macstr + chr(int(value,16))
    return macstr

def isIpUnicast(address):
    if address > "\x00\x00\x00\x00" and address < "\xe0\x00\x00\x00":
        return True
    else:
        return False